<?php

namespace app\admin\controller\cmstostatic;

use app\admin\model\cms\ChannelAdmin;
use app\common\controller\Backend;
use fast\Tree;


/**
 * 系统配置
 *
 * @icon fa fa-gears
 */
class Channel extends Backend
{

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\cms\Archives;
        $cms = get_addon_config('cms');
        if ($cms['archivesdatalimit'] != 'all') {
            $this->dataLimit = $cms['archivesdatalimit'];
        }

        //是否超级管理员
        $this->isSuperAdmin = $this->auth->isSuperAdmin();
        $channelList = [];
        $disabledIds = [];
        $all = collection(\app\admin\model\cms\Channel::order("weigh asc,id asc")->select())->toArray();

        //允许的栏目
        $this->channelIds = $this->isSuperAdmin || !$cms['channelallocate'] ? \app\admin\model\cms\Channel::column('id') : ChannelAdmin::getAdminChanneIds();
        $parentChannelIds = \app\admin\model\cms\Channel::where('id', 'in', $this->channelIds)->column('parent_id');
        $parentChannelIds = array_unique($parentChannelIds);
        $parentChannelList = \think\Db::name('cms_channel')->where('id', 'in', $parentChannelIds)->where('parent_id', '<>', 0)->field('id,parent_id,name')->select();
        $tree = Tree::instance()->init($all, 'parent_id');
        foreach ($parentChannelList as $index => $channel) {
            $parentChannelIds = array_merge($parentChannelIds, $tree->getParentsIds($channel['parent_id'], true));
        }
        foreach ($all as $k => $v) {
            $state = ['opened' => true];
            if ($v['type'] == 'link') {
                $disabledIds[] = $v['id'];
            }
            if ($v['type'] == 'link') {
                $state['checkbox_disabled'] = true;
            }
            if (!$this->isSuperAdmin) {
                if (!in_array($v['id'], $parentChannelIds) && !in_array($v['id'], $this->channelIds)) {
                    unset($all[$k]);
                    continue;
                }
            }
            $channelList[] = [
                'id'     => $v['id'],
                'parent' => $v['parent_id'] ? $v['parent_id'] : '#',
                'text'   => __($v['name']),
                'type'   => $v['type'],
                'state'  => $state
            ];
        }
        $tree = Tree::instance()->init($all, 'parent_id');
        $channelOptions = $tree->getTree(0, "<option model='@model_id' value=@id @selected >@spacer@name</option>", '', $disabledIds);
        $this->view->assign('channelOptions', $channelOptions);
    }


    /**
     * 查看
     */
    public function index()
    {
        $this->staticConfig = get_addon_config('cmstostatic');
        $this->view->assign('staticconfig', $this->staticConfig);

        return $this->view->fetch();
    }
}
